package com.study.www.config;

import com.study.www.enums.ConfigEnum;
import com.study.www.model.Config;
import com.study.www.model.Logger;
import com.study.www.model.mapper.LoggerRepository;
import com.study.www.utils.TaskUtils;
import org.quartz.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


//当上一个任务未结束时下一个任务需进行等待
@DisallowConcurrentExecution
@Component
public class MyJob implements Job {

    //注意此处的 Dao 直接 @Autowired 注入是获取不到的，我们可以通过Spring容器去进行手动注入
    static LoggerRepository loggerRepository;
    //定时任务日志落地
    static List<Logger> loggers=new ArrayList<>();
    //每10条日志进行一下落地
    private final static Integer SIZE=9;

    //execute会根据cron的规则进行执行
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Config config = (Config) jobExecutionContext.getMergedJobDataMap().get(ConfigEnum.SCHEDULEJOB.getCode());
        Long beginTime=null;
        if (config.getIsLogger()){
            beginTime=System.currentTimeMillis();
        }
        TaskUtils.invokMethod(config);
        if (beginTime != null) {
            //手动注入 Dao
            if (MyJob.loggerRepository == null){
                MyJob.loggerRepository = SpringUtils.getBean("loggerRepository");
            }
            saveSysLog(beginTime,config);
        }
    }


    @Async
    void saveSysLog(Long beginTime, Config config) {
        Logger logger = new Logger();
        logger.setBeginTime(beginTime);
        logger.setEndTime(System.currentTimeMillis());
        logger.setClassPath(config.getClassPath());
        logger.setMethName(config.getMethodName());
        logger.setName(config.getName());
        logger.setGroupName(config.getGroup());
        logger.setTime(System.currentTimeMillis()-beginTime);
        logger.setParams(config.getReqParms());
        if (loggers.size() > SIZE) {
            synchronized (MyJob.class) {
                loggerRepository.save(loggers);
                loggers.clear();
            }
        }else{
            loggers.add(logger);
        }
    }

}
